import { Component, OnInit, ViewChild,NgZone } from '@angular/core';
import { Validators, FormBuilder, ValidationErrors, AbstractControl, FormGroup, FormControl } from '@angular/forms';
import { Router, NavigationExtras, ActivatedRoute } from '@angular/router';
import { AlertController } from '@ionic/angular';
// import { AuthTokenService } from '../../../../../services/auth-token.service';
import { AuthTokenService } from '@services/auth-token.service';
import { HttpClient } from "@angular/common/http";
import {TranslateService} from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import { EncryptService } from '@services/encrypt.service';
// import { EncryptService } from '../../../../../services/encrypt.service';
import {CustomToastProviderService} from '@common-components/common-toast/custom-toast-provider.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AppParam } from '@services/common-service.service';

@Component({
  selector: 'app-payment-password',
  templateUrl: './payment-password.page.html',
  styleUrls: ['./payment-password.page.scss'],
})
export class PaymentPasswordPage implements OnInit {
  title = "Please enter your password";
  btnName = 'Confirm';
  resetBtn = false;
  rows=[];

  @ViewChild('submitBtn',{static:true}) submitBtn;
  paymentPwdForm!: FormGroup
  i18n:any;
  initForm(){
    this.rows = [
      {
        inputTitle: this.i18n.new_password,
        placeholder: 'Enter',
        inputName: 'newPassword',
        hidden: false
      },
      {
        inputTitle: this.i18n.confirm_password,
        placeholder: 'Enter',
        inputName: 'confirmPassword',
        hidden: false
      }
    ];
  }

  appUserId = this.authTokenService.getAppUserId();
  pageTitle = 'PAYMENT PASSWORD';
  formTitle = '';
  PaymentPasswordReset = false;
  resetToast:boolean;
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    public alertController: AlertController,
    private authTokenService: AuthTokenService,
    private http: HttpClient,
    private translate: TranslateService,
    private encryptService:EncryptService,
    private defaultLanguageService:DefaultLanguageService,
    private customToast:CustomToastProviderService,
    private ngZone:NgZone,
    private commonService:CommonService
  ) {
 
     // this.paymentPwdForm.reset();
     this.paymentPwdForm = this.fb.group({
      newPassword:  new FormControl('',{
        validators:[Validators.required,Validators.pattern(/^[0-9]{6}$/)]
      }),
      confirmPassword:  new FormControl('',{
        validators:[Validators.required,Validators.pattern(/^[0-9]{6}$/)]
      }),
    },{
      updateOn:'blur',
      validators: this.passwordMatchValidator
      // asyncValidators:this.passwordMatchValidator
    });
    this.paymentPwdForm.reset();
   
    this.i18n = this.commonService.initTranslate(['myAccount.setting.payment_settings.password_setting']);
    this.initForm();
    this.firstCheck();
  }

  get newPassword(){
    return this.paymentPwdForm.get('newPassword');
  }

  get confirmPassword(){
    return this.paymentPwdForm.get('confirmPassword');
  }

  get oldPassword(){
    return this.paymentPwdForm.get('oldPassword');
  }


  checkNewPwd(){
    return (ctrl: AbstractControl) => {
      return new Promise(resolve => {
        if(ctrl.parent.value.oldPassword){
          if(ctrl.value === ctrl.parent.value.oldPassword){
            resolve({ msg: 'The new password cannot be the same as the old password',error:true });
          }else{
            resolve(null);
          }
        }else{
          resolve(null);
        }
      });
    };
  }

  titleBackUrl:string = '/tabs/myAccount/setting/payment-settings';
  firstCheck(){
    //reset = > payment
    this.activatedRoute.queryParams.subscribe((data)=>{
      if(data.url){
        this.titleBackUrl = data.url;
      }
      if(data.resetPwd){
        this.pageTitle = data.pageTitle;
        this.formTitle = data.formTitle;
        this.PaymentPasswordReset = true;
        this.resetToast = true;
   
        this.resetBtn = false;
        let old = this.rows.find(value=>value.inputName=='oldPassword');
        old.hidden=true;
        this.oldPwdValidate = false;
        this.paymentPwdForm.removeControl('oldPassword');
      }else{
        this.pageTitle =this.i18n.page_title;
        this.formTitle = this.i18n.password_title;
        this.PaymentPasswordReset = false;
        this.resetToast = false;
        // setting => payment
        this.checkPaymentPwdExistence();
      }
    });
  }

  ngOnInit() {
 

    
  }

  passwordMatchValidator(g: FormGroup) {
    // return ((g: FormGroup) => {
    //   return new Promise(resolve => {
       
    //   });
    // });
    let npwd = g.get('newPassword').value;
    let cpwd = g.get('confirmPassword').value;
    let oldPassword = g.get('oldPassword');

    let npwdPattern = g.get('newPassword').hasError('pattern');
    let cpwdPattern = g.get('confirmPassword').hasError('pattern');
    let opwdPattern = null;
    if(oldPassword){
      opwdPattern = oldPassword.hasError('pattern');
      if(!npwd && !cpwd  && !npwdPattern && !cpwdPattern && !opwdPattern){
        return { 'match': false,'allMatch':false } ;
      }
      
      if(cpwd){
        return (npwd === cpwd && !npwdPattern && !cpwdPattern && !opwdPattern) ?  { 'match': true,'allMatch':true }
        :  { 'match': false,'allMatch':false };
      }
    }else{

      if(!npwd && !cpwd  && !npwdPattern && !cpwdPattern){
        return { 'match': false,'allMatch':false } ;
      }
      
      if(cpwd){
        return (npwd === cpwd && !npwdPattern && !cpwdPattern) ?  { 'match': true,'allMatch':true }
        :  { 'match': false,'allMatch':false };
      }
    }
  }


  toNext() {
    let url = '/scm/app/repeatLoginPwd.do';
    let paymentPwd = this.paymentPwdForm.value.confirmPassword;
    let newPassword = this.paymentPwdForm.value.newPassword;
    let oldPassword = this.paymentPwdForm.value.oldPassword;
    if(newPassword == oldPassword){
      this.customToast.show({
          icon:false,
          iconSuccess:false,
          message:'The new password cannot be the same as the old password',
          duration:2000
        });
      this.paymentPwdForm.reset();
      return ;
    }

    if(this.oldPwdValidate && this.paymentPwdForm.get('oldPassword')){
      let old = this.paymentPwdForm.get('oldPassword').value;
      if(!old){
        this.customToast.show({
          icon:false,
          iconSuccess:false,
          message:'Old password error',
          duration:2000
        });
        this.paymentPwdForm.reset();
        return;
      }
    }
    paymentPwd = this.encryptService.md5Ecrypt(paymentPwd);

    let requestData = {
      appUserId:this.appUserId,//this.authTokenService.getAppUserId(),
      paymentPwd:paymentPwd,
      currDeviceNumber: '333'
    };
    this.http.post(url, requestData).subscribe((response: CommonResponse) => {

      let body = response.responseBody;
      if (body.repeatLoginPwd) {
        let alertController = this.alertController;
        let paymentForm = this.paymentPwdForm;
        (async function alert(){
          const alert = await alertController.create({
            header: 'The payment password cannot be the same as the login password',
            buttons: [
              {
                text: 'Cancel',
                role: 'cancel',
                cssClass: 'secondary',
                handler: () => {
                
                  paymentForm.reset();
                }
              }, {
                text: 'Confirm',
                handler: () => {
               
                  paymentForm.reset();
                }
              }
            ]
          });
          await alert.present();
        })();
        
        return;
      }

      let router = this.router;
      //1.request
      let url = '/scm/app/changePaymentPwd.do';
      paymentPwd = this.paymentPwdForm.value.confirmPassword;
      paymentPwd = this.encryptService.md5Ecrypt(paymentPwd);
      let requestData = {
        appUserId:this.appUserId,//this.authTokenService.getAppUserId(),
        paymentPassword:paymentPwd,
        currDeviceNumber: '333'
      };
      this.http.post(url, requestData).subscribe((response: CommonResponse) => {
        //2.alert
        if(response.isSuccess){
          let navigationExtras: NavigationExtras = {
            queryParams: {
              createPaymentPwd:true,
              text:this.resetToast?'Updated Successfully':'Create Successfully'
            } 
          };
          router.navigate([this.titleBackUrl],navigationExtras);
        }
      });

    });

  }
  
  oldPwdValidate:boolean = false;
  checkPwd(){
    return (ctrl: AbstractControl) => {
      return new Promise(resolve => {
        if(!ctrl.value){
          return resolve(  { "oldPwderror":false });
        }
        let pwd = this.encryptService.md5Ecrypt(ctrl.value);
        this.http.post('/scm/app/checkOldPwd.do', {
          appUserId: this.appUserId,//this.authTokenService.getAppUserId(),
          paymentPwd:pwd
        }).subscribe((response: CommonResponse) => {
          if(response.responseBody.oldPwd){
            this.oldPwdValidate=true;
            return resolve( { "oldPwderror":true } );
          }else{
            // this.submitBtn.el.disabled=false;
            this.oldPwdValidate=false;
            return resolve(  { "oldPwderror":false });
          }
        });
      });
    };
  }

  changeView() {
    this.title = "Change Your  Pay Password";
    this.resetBtn = true;
    this.resetToast=true;
    this.paymentPwdForm.addControl('oldPassword',
      new FormControl('',{
        validators:[Validators.required,Validators.pattern(/^[0-9]{6}$/)],//Validators.required,
        updateOn:'blur',
        asyncValidators:this.checkPwd()
      })
    );

    this.rows = [
      {
        inputTitle: this.i18n.old_password,
        placeholder: 'Enter',
        inputName: 'oldPassword',
        hidden: false
      },
      {
        inputTitle:  this.i18n.new_password,
        placeholder: 'Enter',
        inputName: 'newPassword',
        hidden: false
      },
      {
        inputTitle:  this.i18n.confirm_password,
        placeholder: 'Enter',
        inputName: 'confirmPassword',
        hidden: false
      }
    ];

    this.paymentPwdForm.reset();
  }
  
  checkPaymentPwdExistence(){
    this.activatedRoute.data.subscribe((obj)=>{
      let body = obj.data.responseBody;
      if (!body.firstPwd) {
        this.changeView();
      }
    });

    this.paymentPwdForm.reset();
  }

  ngAfterViewInit(): void {

    
  }

  toReset() {
    this.router.navigate(['/tabs/myAccount/setting/payment-settings/payment-password/password-reset']);
  }
}
